/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode middleNode(ListNode head) {
        // Time complexity: O(n)
        // Space complexity: O(n)
        /*if(head == null || head.next == null) {
            return head;
        }
        List<ListNode> list = new ArrayList<>();
        ListNode temp = head;

        while(temp != null) {
            list.add(temp);
            temp = temp.next;
        }

        // 1 -> 2 -> 3
        // 1 -> 2 -> 3 -> 4

        return list.get(list.size() / 2);*/
        // Time complexity: O(n)
        // Space complexity: O(1)
        ListNode turtle = head, rabbit = head;

        while(rabbit != null && rabbit.next != null) {
            rabbit = rabbit.next.next;
            turtle = turtle.next;
        }


        return turtle;

        
    }
}